<?php

namespace App\Store\Services\Message;

use App\Store\Models\Account\Account;
use App\Store\Models\Member\Member;
use App\Store\Models\Wxapp\WxaccountSetting;
use App\Store\Models\Wxapp\WxaccountTemplate;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Support\Facades\Log;

class WxaccountMessage
{
    public static function sendwx($cp_id, $open_id, $type, $order_info=[])
    {
        if (in_array($type, ['sales_order', 'deposit_order', 'recharge_order', 'recovery_order'])) {
            $memInfo = Member::where(['id' => $open_id, 'is_del'=>1])->first();
            if (!$memInfo) {
                return ['code' => '001', 'msg' => '用户为空'];
            }
            $memInfo = $memInfo->toArray();
            if (!isset($memInfo['wx_account_open_id'])) {
                return ['code' => '001', 'msg' => 'open_id为空'];
            }
            $open_id = $memInfo['wx_account_open_id'];
        }
        self::api($cp_id, $open_id, $type, $order_info);
        return;
    }

    public static function sendwxinner($cp_id, $store_id, $type, $order_info=[])
    {
        $query = Account::where(['cp_id' => $cp_id, 'is_sendorder_msg' => 1, 'is_del' => 1])->where('wx_account_openid', '!=', '');
        $query->where(function ($q) use ($store_id) {
            $q->where('store_ids','')->orWhereRaw('FIND_IN_SET(?,store_ids)',[$store_id]);
        });
        $list = $query->get();
        if (!$list) {
            return ['code' => '001', 'msg' => '用户为空'];
        }
        $list = $list->toArray();
        foreach ($list as $item) {
            self::api($cp_id, $item['wx_account_openid'], $type, $order_info);
        }
        return;
    }

    public static function api($cp_id, $open_id, $type, $order_info)
    {
        $info = WxaccountTemplate::where([['cp_id', $cp_id]])->first();
        if (empty($info[$type])) {
            return ['code' => '001', 'msg' => '发送失败，模板id为空'];
        }
        $temp_id = $info[$type];

        $setting = WxaccountSetting::where([['cp_id', $cp_id]])->first();
        if(!$setting){
            return ['code' => '001', 'msg' => '发送失败，未配置微信支付'];
        }
        $setting = $setting->toArray();
        $config = [
            'app_id' => $setting['appid'],
            'secret' => $setting['appsecret'],
        ];

        $wxapp = new Application($config);
        $accessToken = $wxapp->getAccessToken();
        $token = $accessToken->getToken();

        $api = $wxapp->getClient();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;

        $data = self::getdata($type, $order_info);
        $sale_url ='';
        if (!empty($type)&& in_array($type,['recovery_order','sales_order'])) {
            $sale_url = env('ORDER_URL') . '?cp_id='.$cp_id.'&order_id='.$order_info['id'].'&type='.$type;
        }

        $body = [
            'touser' => $open_id,
            'template_id' => $temp_id,
            'data' => $data,
            'url' => empty($sale_url)? '': $sale_url
        ];
        return $api->post($url, [
            'body' => json_encode($body, JSON_THROW_ON_ERROR)
        ]);
    }

    public static function getdata($type, $order_info){
        switch ($type) {
            case 'sales_order':
                $data = [
                    'character_string14' => [
                        'value' => $order_info['order_sn']
                    ],
                    'phrase9' => [
                        'value' => $order_info['pay_type_name']
                    ],
                    'amount3' => [
                        'value' => bcdiv($order_info['total_money'],100,2)
                    ],
                    'amount22' => [
                        'value' =>$order_info['real_money']/100
                    ],
                    'character_string35' => [
                        'value' => $order_info['order_points']+$order_info['order_points_recovery']
                    ],
                ];
                break;
            case 'deposit_order':
                $data = [
                    'time1' => [
                        'value' => date('Y-m-d H:i:s', $order_info['create_at'])
                    ],
                    'amount2' => [
                        'value' => $order_info['change_before']/100
                    ],
                    'amount3' => [
                        'value' => $order_info['money']/100
                    ],
                    'amount4' => [
                        'value' => '0.00'
                    ],
                    'amount5' => [
                        'value' => $order_info['change_after']/100
                    ],
                ];
                break;
            case 'recharge_order':
                $data = [
                    'time1' => [
                        'value' => date('Y-m-d H:i:s', $order_info['create_at'])
                    ],
                    'amount2' => [
                        'value' => $order_info['change_before']/100
                    ],
                    'amount3' => [
                        'value' => $order_info['money']/100
                    ],
                    'amount4' => [
                        'value' => $order_info['send_money']/100
                    ],
                    'amount5' => [
                        'value' => $order_info['change_after']/100
                    ],
                ];
                break;
            case 'recovery_order':
                $data = [
                    'character_string2' => [
                        'value' => $order_info['order_sn']
                    ],
                    'thing13' => [
                        'value' => '纯回收订单'
                    ],
                    'amount8' => [
                        'value' => $order_info['money']/100
                    ],
                    'number4' => [
                        'value' => $order_info['count']
                    ],
                    'time11' => [
                        'value' => date('Y-m-d H:i:s', $order_info['create_at'])
                    ],
                ];
                break;
        }
        return $data;
    }
}
